layui.extend({
    yjUrl: '../../main/config/yjUrl',
    main: '../../main/config/lib/main',
    dropdown: '/res/js/extend/dropdown/dropdown'
}).define(['dropdown', 'main', 'table', 'form', 'yjUrl', 'jm'], function(exports) {
    var $ = layui.$,
        table = layui.table,
        dropdown = layui.dropdown,
        yjUrl = layui.yjUrl,
        setter = parent.layui.setter,
        layer = parent.layui.layer,
        admin = parent.layui.admin,
        jm = layui.jm,
        local = layui.data(setter.tableName),
        objDom, $body = $('body'),
        $input = $('#scene-select .layui-input'),
        $inputVal = $('#scene-select #InputValue'),
        main = layui.main,
        rootPath = '',
        yj_system_users = {
            setRootPath: function(url) {
                rootPath = setter.views + url + '/';
            },
            setEmptyQueryKey: function() {
                let queryKey = {};
                $("dl dd").each(function(index, item) {
                    queryKey[$(item).attr('lay-value')] = '';
                });
                return queryKey;
            }
        };

    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substring(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        }
        return "";
    }
    var type = getQueryString("type");
    if (type == '1') {
        $("#add").show();
    }

    //加载列表
    table.render({
        elem: '#LAY-app-users-list',
        url: yjUrl.find('system/users/Query').urlPath + '?type=' + type,
        headers: main.headerToken(),
        title: '数据表',
        page: true,
        cols: [
            [{ type: 'checkbox', fixed: 'left' }, { field: 'username', title: '用户名' }, { field: 'truename', title: '真实姓名' }, { field: 'deptname', title: '单位名称' }, { field: 'remark', title: '所属科室' }, { field: 'phonenumber', title: '联系电话' }, { field: 'email', title: '电子邮箱' }, {
                field: 'loginstate',
                title: '账号状态',
                width: 100,
                templet: function(d) {
                    if (d.isenabled == "0") {
                        return '<span style="border-radius: 2px;text-align: center;color:#1890ff;background:#e6f7ff;border:1px solid #91d5ff;height: 20px;line-height: 19px;box-sizing: border-box;position: relative;display: inline-block;padding: 0 6px;font-size: 12px;">正常</span>';
                    } else {
                        return '<span style="border-radius: 2px;text-align: center;color:#f5222d;background:#fff1f0;border:1px solid #ffa39e;height: 20px;line-height: 19px;box-sizing: border-box;position: relative;display: inline-block;padding: 0 6px;font-size: 12px;">锁定</span>';
                    }
                }
            }, { title: '账号操作', width: 280, align: 'center', fixed: 'right', toolbar: '#tablerole' }, { title: '操作', width: 100, align: 'center', fixed: 'right', toolbar: '#LAY-app-users-toolbar' }]
        ],
        text: '对不起，加载出现异常！',
        height: 'full-190',
        done: function(res) {
            dropdown.suite();
            for (var i = 0; i < res.data.length; i++) {
                dropdown.onFilter("cz" + res.data[i].id, function(event) {
                    var option = event.split('-');
                    if (option[1] == "detail") {
                        //用表传参
                        layui.data(setter.tableName, { key: 'yj_KeyID', value: option[0] });
                        parent.layui.admin.popupChild({
                            type: 2,
                            title: '详情',
                            anim: 1,
                            closeBtn: 1,
                            maxmin: true,
                            area: ['800px', '600px'],
                            content: [setter.views + 'system/users/yj_system_users_info.html', 'on'],
                            success: function(layero, index) {
                                var containerDiv = layero.find('iframe').contents().find("#layui-body-content"),
                                    btn = layero.find(".layui-layer-btn a"),
                                    title = layero.find(".layui-layer-title");
                                if (local['yj_FontSize']) {
                                    containerDiv.addClass('layui-fontsize-' + local['yj_FontSize']);
                                    if (local['yj_FontSize'] == 'big') {
                                        btn.css("font-size", setter.fontSize.big);
                                        title.css("font-size", setter.fontSize.big);
                                    } else if (local['yj_FontSize'] == 'extrabig') {
                                        btn.css("font-size", setter.fontSize.extrabig);
                                        title.css("font-size", setter.fontSize.extrabig);
                                    }
                                }
                            }
                        });
                    } else if (option[1] == "edit") {
                        //用表传参
                        layui.data(setter.tableName, { key: 'yj_KeyID', value: option[0] });
                        parent.layui.admin.popupChild({
                            type: 2,
                            title: '修改',
                            anim: 1,
                            closeBtn: 1,
                            maxmin: true,
                            area: ['800px', '600px'],
                            content: [setter.views + 'system/users/yj_system_users_edit.html', 'on'],
                            btn: ['修改', '关闭'],
                            btnAlign: 'c',
                            success: function(layero, index) {
                                var containerDiv = layero.find('iframe').contents().find("#layui-body-content");
                                if (local['yj_FontSize']) {
                                    containerDiv.addClass('layui-fontsize-' + local['yj_FontSize']);
                                }
                            },
                            yes: function(index, layero) {
                                var iframeWindow = parent.window['layui-layer-iframe' + index],
                                    submit = layero.find('iframe').contents().find("#YjbtnSave");

                                //监听提交
                                iframeWindow.layui.form.on('submit(YjbtnSave)', function(data) {
                                    admin.req({
                                        url: 'system/users/Update',
                                        data: JSON.stringify(data.field),
                                        type: 'put',
                                        done: function(res) {
                                            if (res.successful) {
                                                main.msg_success(res.msg);
                                                table.reload('LAY-app-users-list', { where: { time: new Date() } });
                                            } else {
                                                main.msg_error(res.msg);
                                            }
                                        }
                                    });
                                    layer.close(index); //关闭弹层 
                                });
                                submit.trigger('click');
                            },
                            cancel: function() {
                                layer.closeAll();
                            }
                        });
                    } else if (option[1] == "del") {
                        layer.confirm('确定删除吗？', function(index) {
                            admin.req({
                                url: 'system/users/Delete',
                                type: 'delete',
                                data: { id: option[0] },
                                done: function(res) {
                                    table.reload('LAY-app-users-list', { where: { time: new Date() } });
                                    admin.msg_success(res.msg);
                                }
                            });
                            layer.close(index);
                        });
                    }
                });
            }
        }
    });

    //监听表格行
    table.on('tool(LAY-app-users-list)', function(obj) {
        var data = obj.data; //获得当前行数据
        var uid = data.id;
        if (obj.event == 'select') {
            parent.layui.admin.popupChild({
                type: 2,
                title: '修改角色',
                anim: 1,
                closeBtn: 1,
                maxmin: true,
                area: ['500px', '400px'],
                content: [setter.views + 'system/users/yj_system_users_role.html?uid=' + uid, 'on'],
                btn: ['保存', '关闭'],
                btnAlign: 'c',
                success: function(layero, index) {
                    var containerDiv = layero.find('iframe').contents().find("#layui-body-content");
                    if (local['yj_FontSize']) {
                        containerDiv.addClass('layui-fontsize-' + local['yj_FontSize']);
                    }
                },
                yes: function(index, layero) {
                    var submit = layero.find('iframe').contents().find("#YjbtnSave");
                    submit.trigger('click');
                },
                cancel: function() {
                    layer.closeAll();
                }
            });
        } else if (obj.event === 'ResetPWD') { //重置密码
            layer.confirm('确定要重置用户密码吗？', function(index) {
                admin.req({
                    url: 'system/users/ResetPWD',
                    type: 'get',
                    data: { id: data.id },
                    done: function(res) {
                        if (res.successful) {
                            admin.msg_success("密码重置成功，重置后密码为：123456aA@");
                        } else {
                            admin.msg_success("密码重置失败！");
                        }
                    }
                });
                layer.close(index);
            });
        } else if (obj.event == "JieSuo") {
            layer.confirm('确定要解锁吗？', function(index) {
                admin.req({
                    url: 'system/users/JieSuo',
                    type: 'get',
                    data: { id: data.id },
                    done: function(res) {
                        if (res.successful) {
                            table.reload('LAY-app-users-list', { where: { time: new Date() } });
                            admin.msg_success("解锁成功！");
                        } else {
                            admin.msg_success("解锁失败！");
                        }
                    }
                });
                layer.close(index);
            })
        }
    });

    table.on('sort(LAY-app-users-list)', function(obj) {
        dropdown.suite();
    });

    //事件
    var active = {
        Yjbatchdel: function() {
            var checkStatus = table.checkStatus('LAY-app-users-list'),
                checkData = checkStatus.data,
                idData = new Array(); //得到选中的数据 
            if (checkData.length === 0) {
                return admin.msg_error("选择删除数据！");
            } else {
                for (var i = 0; i < checkData.length; i++) {
                    idData.push(checkData[i].id);
                }
                layer.confirm('确定删除吗？', function(index) {
                    admin.req({
                        url: 'system/users/BatchDelete',
                        type: 'delete',
                        data: { id: idData.join(",") },
                        done: function(res) {
                            table.reload('LAY-app-users-list', { where: { time: new Date() } });
                            admin.msg_success(res.msg);
                        }
                    });
                    layer.close(index);
                });
            }
        },
        Yjsearch: function() {
            let queryKey = yj_system_users.setEmptyQueryKey(); //清空
            var keywords = $("#searchKeyword").val();
            queryKey[$inputVal.val()] = keywords;
            table.reload('LAY-app-users-list', {
                where: queryKey,
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        }
    }

    $('.layui-btn.layuiadmin-btn-users-list').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    dropdown.suite("[lay-filter='scene-select']", {
        template: "#Scene-dropdown",
        gap: 10,
        showBy: 'hover',
        success: function($dom) {
            objDom = $dom;
            objDom.find("dd").click(function() {
                var $this = $(this);
                $this.addClass("layui-this").siblings("dd").removeClass("layui-this");
                var value = $this.attr('lay-value');
                var text = $this.html();
                $input.val(value ? $.trim(text) : '');
                $inputVal.val(value);
                objDom.removeClass("layui-show");
                $("#searchKeyword").focus();
            });
        }
    });

    //鼠标移开隐藏
    $("#searchKeyword").mouseover(function() {
        objDom.removeClass("layui-show");
    });

    /* 添加/修改弹出层 */
    $body.on("click", ".open-popup", function() {
        var caoZuo = $(this).attr("data-caozuo"),
            title = $(this).attr("title"),
            url = $(this).attr("data-url"),
            opentype = $(this).attr("open-type"),
            size = $(this).attr("data-size");

        //自动设置全路径
        if (rootPath != '') {
            url = rootPath + url;
        }
        main.mainpopup({
            caoZuo: caoZuo,
            url: url,
            opentype: opentype,
            size: size,
            title: title,
            yes: function(index, layero) {
                var iframeWindow = parent.window['layui-layer-iframe' + index],
                    submit = layero.find('iframe').contents().find("#YjbtnSave");
                //监听提交
                iframeWindow.layui.form.on('submit(YjbtnSave)', function(data) {
                    if (caoZuo == 'add') {
                        var reg1 = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/;
                        if (reg1.test(data.field.password)) {
                            data.field.type = 1;
                            admin.req({
                                url: 'system/users/Add',
                                data: JSON.stringify(data.field),
                                type: 'post',
                                done: function(res) {
                                    if (res.successful) {
                                        main.msg_success(res.msg);
                                        table.reload('LAY-app-users-list', { where: { time: new Date() } });
                                    } else {
                                        main.msg_error(res.msg);
                                    }
                                }
                            });
                        } else {
                            layer.msg("密码长度8位以上（包含8位），至少1个大写字母，1个小写字母，1个数字和一个特殊字符！");
                            return false;
                        }
                    } else if (caoZuo == 'search') {
                        table.reload('LAY-app-users-list', {
                            where: data.field,
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                    }
                    layer.close(index); //关闭弹层
                });
                submit.trigger('click');
            }
        });
    });

    /* 导出弹出层 */
    $body.on("click", ".open-popup-export", function() {
        main.exportPopup();
    });

    /* 关闭弹出层 */
    $(".close-popup").click(function(e) {
        e.preventDefault();
        parent.layer.close(window.parent.layerIndex);
    });

    exports('yj_system_users', yj_system_users);
});